package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.LoginMapper;
import com.heima.admin.service.LoginService;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdUser> implements LoginService {

    /**
     * 用户登录功能实现
     *
     * @param dto 封装数据对象
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO dto) {

        //获取用户名
        String name = dto.getName();
        //获取密码
        String password = dto.getPassword();
        //判断名字是否存在
        if (StringUtils.isBlank(name)||StringUtils.isBlank(password)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名密码不能为空!");        }
        //查询表中是否有该用户
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户不存在");
        }
        //判断密码  密码+salt盐
        String md5Pwd = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes(StandardCharsets.UTF_8));
        if (!md5Pwd.equals(user.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"登录密码错误!");
        }
        //判断状态是否等于9
        if(9!=user.getStatus().intValue()){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常，请联系管理员");
        }
        //修改登录时间
        user.setLoginTime(new Date());
        //修改用户信息
        updateById(user);
        //拿到token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        //创建vo对象,将敏感数据剔除
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user,userVO);
        //创建map集合
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",userVO);
        //将结果返回
        return ResponseResult.okResult(map);
    }
}
